package com.neusoft.neuiotms.dcom.converter;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.file.service.FileService;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.KnowledgeAttachmentDTO;
import com.neusoft.neuiotms.dcom.dto.KnowledgeCommentDTO;
import com.neusoft.neuiotms.dcom.dto.KnowledgeDTO;
import com.neusoft.neuiotms.dcom.model.Knowledge;
import com.neusoft.neuiotms.dcom.model.KnowledgeAttachment;
import com.neusoft.neuiotms.dcom.model.KnowledgeComment;
import com.neusoft.neuiotms.dcom.model.KnowledgeKeywords;
import com.neusoft.neuiotms.dcom.repository.KnowledgeAttachmentRepository;
import com.neusoft.neuiotms.dcom.repository.KnowledgeCommentRepository;
import com.neusoft.neuiotms.dcom.repository.KnowledgeKeywordsRepository;
import com.neusoft.neuiotms.dcom.repository.KnowledgeRepository;
import com.neusoft.neuiotms.dcom.repository.KnowledgeTypeRepository;

@Component
public class KnowledgeConverter extends AbstractConverter<Knowledge, KnowledgeDTO> {

    @Autowired
    private FileService fileService;

    @Autowired
    private KnowledgeRepository knowledgeRepository;

    @Autowired
    private KnowledgeAttachmentConverter knowledgeAttachmentConverter;

    @Autowired
    private KnowledgeAttachmentRepository knowledgeAttachmentRepository;

    @Autowired
    private KnowledgeCommentConverter knowledgeCommentConverter;

    @Autowired
    private KnowledgeCommentRepository knowledgeCommentRepository;

    @Autowired
    private KnowledgeKeywordsConverter knowledgeKeywordConverter;

    @Autowired
    private KnowledgeKeywordsRepository knowledgeKeywordsRepository;

    @Autowired
    private KnowledgeTypeRepository knowledgeTypeRepository;

    @Override
    public Knowledge toModel(final KnowledgeDTO dto) {
        Knowledge model;

        if (dto.isNew()) {
            model = new Knowledge();
        } else {
            model = this.knowledgeRepository.getOne(dto.getId());
        }
        model.setContent(dto.getContent());
        model.setReadingVolume(dto.getReadingVolume());
        model.setTitle(dto.getTitle());
        model.setUpdateTime(dto.getUpdateTime());
        model.setUpdateUserCode(dto.getUpdateUserCode());
        model.setUpdateUserName(dto.getUpdateUserName());
        model.setUserCode(dto.getUserCode());
        model.setUserName(dto.getUserName());
        if (!StringUtils.isEmpty(dto.getKnowledgeTypeCode())) {
            model.setType(this.knowledgeTypeRepository.findByCode(dto.getKnowledgeTypeCode()));
        }

        //附件
        final List<KnowledgeAttachment> attachment = model.getAttachment().stream().collect(Collectors.toList());
        final List<String> fsIds =
                dto.getAttachment() == null ? new ArrayList<>() : dto.getAttachment().stream()
                        .map(KnowledgeAttachmentDTO::getFsId).collect(Collectors.toList());
        attachment.forEach(k -> {
            if (!fsIds.contains(k.getFsId())) {
                model.getAttachment().remove(k);
                this.knowledgeAttachmentRepository.delete(k);
                this.deleteMongoFile(k.getFsId(), model.getId());
            }
        });
        if (CollectionUtils.isNotEmpty(dto.getAttachment())) {
            dto.getAttachment().stream().map(t -> {
                final KnowledgeAttachment attach = this.knowledgeAttachmentConverter.toModel(t);
                attach.setKnowledge(model);
                return attach;
            }).forEach(model.getAttachment()::add);
        }
        //评论
        final List<KnowledgeComment> comment = model.getComment().stream().collect(Collectors.toList());
        final List<Long> ids = dto.getComment() == null ? new ArrayList<>()
                : dto.getComment().stream().map(KnowledgeCommentDTO::getId).collect(Collectors.toList());
        comment.forEach(k -> {
            if (!ids.contains(k.getId())) {
                model.getComment().remove(k);
                this.knowledgeCommentRepository.delete(k);
            }
        });
        if (CollectionUtils.isNotEmpty(dto.getComment())) {
            dto.getComment().stream().map(t -> {
                final KnowledgeComment com = this.knowledgeCommentConverter.toModel(t);
                com.setKnowledge(model);
                return com;
            }).forEach(model.getComment()::add);
        }
        //关键字
        final List<KnowledgeKeywords> keywords = model.getKeywords().stream().collect(Collectors.toList());
        keywords.forEach(k -> {
            model.getKeywords().remove(k);
            this.knowledgeKeywordsRepository.delete(k);
        });
        if (CollectionUtils.isNotEmpty(dto.getKeywords())) {
            dto.getKeywords().stream().map(t -> {
                final KnowledgeKeywords key = this.knowledgeKeywordConverter.toModel(t);
                key.setKnowledge(model);
                return key;
            }).forEach(model.getKeywords()::add);

        }
        return model;
    }

    @Override
    public KnowledgeDTO toDTO(final Knowledge model, final boolean forListView) {
        final KnowledgeDTO dto = new KnowledgeDTO();

        dto.setContent(model.getContent());
        dto.setCreateTime(model.getCreateTime());
        dto.setId(model.getId());
        dto.setReadingVolume(model.getReadingVolume());
        dto.setTitle(model.getTitle());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setUpdateUserCode(model.getUpdateUserCode());
        dto.setUpdateUserName(model.getUpdateUserName());
        dto.setUserCode(model.getUserCode());
        dto.setUserName(model.getUserName());
        dto.setKnowledgeTypeCode(model.getType().getCode());
        dto.setKnowledgeTypeName(model.getType().getName());
        if (!forListView) {
            dto.setAttachment(this.knowledgeAttachmentConverter.toListDTO(model.getAttachment()));

        }
        dto.setKeywords(this.knowledgeKeywordConverter.toListDTO(model.getKeywords()));
        dto.setComment(this.knowledgeCommentConverter.toListDTO(model.getComment()));
        if ((model.getKeywords() != null) && !model.getKeywords().isEmpty()) {
            dto.setKeywordsName(
                    model.getKeywords().stream().map(KnowledgeKeywords::getName).collect(Collectors.toList()));
        }

        return dto;
    }

    private void deleteMongoFile(final String fsId, final long id) {
        final List<KnowledgeAttachment> list = this.knowledgeAttachmentRepository.findByFsId(fsId);
        boolean flag = false;//判断是否有其他knowledge关联同一张图片
        for (final KnowledgeAttachment attach : list) {
            if (attach.getKnowledge().getId().longValue() != id) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            this.fileService.deleteByFsId(fsId);
        }
    }

}
